import logging
import dashscope
import random
from dashscope import Generation
from http import HTTPStatus
from .. import AiAdapter, AiQuery, AiQueryResult
from flask import current_app
from config.config import AppConfig
from api.home.service import HomeService
from common import Result

LOGGER = logging.getLogger(__name__)






# qwen-max 效果明显很准确
# qwen-plus 加很多明确要求不要加的字段，结果解析不出来
# qwen-tubor 总是中间省略掉内容，经常解析不出来
# 'qwen1.5-0.5b-chat', 这个模型回答错误很多


_MODEL_NAME = "qwen-max"

class Qianwen(AiAdapter):
    def query(self, query: AiQuery) -> AiQueryResult:

        try:
            res: Result = HomeService().getSetting()
            API_KEY = res.data['apikeyQianwen']
            LOGGER.info(f"qianwen读取到的key是: {API_KEY}")
            dashscope.api_key = API_KEY
            if not res.is_success():
                return AiQueryResult(isValid=False, errMessage="请在配置页面，填写配置")
        except Exception as e:
            LOGGER.exception(e)
            return AiQueryResult(
                isValid=False, errMessage=f"请在配置页面，填写配置:{str(e)}"
            )

        try:
            LOGGER.info(query.userMessage)

            messages = [
                {"role": "user", "content": query.userMessage},
            ]
            response = Generation.call(
                _MODEL_NAME,
                messages=messages,
                seed=random.randint(1, 10000),
                result_format="message",
            )
            LOGGER.info(response)

            if response.status_code == HTTPStatus.OK:

                return AiQueryResult(
                    text=response["output"]["choices"][0]["message"]["content"],
                    totalToken=response["usage"]["total_tokens"],
                )

            else:
                LOGGER.error(
                    "Request id: %s, Status code: %s, error code: %s, error message: %s"
                    % (
                        response.request_id,
                        response.status_code,
                        response.code,
                        response.message,
                    )
                )
            return AiQueryResult(isValid=False, errMessage=response.message)
        except Exception as e:
            LOGGER.exception(e)
            return AiQueryResult(isValid=False, errMessage=str(e))
